package main

import (
	"log"
	"net/http"
	"strings"

	"personal-blog/config"
	"personal-blog/controllers"
	"personal-blog/middleware"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
)

func main() {
	// 初始化日志
	logrus.SetFormatter(&logrus.JSONFormatter{})
	logrus.SetLevel(logrus.InfoLevel)

	// 初始化数据库
	config.InitDatabase()

	// 设置Gin模式
	gin.SetMode(gin.ReleaseMode)

	// 创建Gin路由器
	r := gin.Default()

	// 添加中间件
	r.Use(middleware.CORSMiddleware())
	r.Use(gin.Logger())
	r.Use(gin.Recovery())

	// 静态文件服务 - 禁用缓存以便开发调试
	r.StaticFS("/static", http.Dir("./static"))
	r.Use(func(c *gin.Context) {
		if strings.HasPrefix(c.Request.URL.Path, "/static/") {
			c.Header("Cache-Control", "no-cache, no-store, must-revalidate")
			c.Header("Pragma", "no-cache")
			c.Header("Expires", "0")
		}
		c.Next()
	})
	r.LoadHTMLGlob("templates/*")

	// 前端页面路由
	r.GET("/", func(c *gin.Context) {
		c.HTML(200, "index.html", gin.H{
			"title": "个人博客系统",
		})
	})

	// 我的文章页面路由
	r.GET("/my-posts", func(c *gin.Context) {
		c.HTML(200, "my-posts.html", gin.H{
			"title": "我的文章 - 个人博客",
		})
	})

	// API路由组
	api := r.Group("/api/v1")
	{
		// 认证相关路由
		auth := api.Group("/auth")
		{
			auth.POST("/register", controllers.Register)
			auth.POST("/login", controllers.Login)
			auth.GET("/profile", middleware.AuthMiddleware(), controllers.GetProfile)
		}

		// 文章相关路由
		posts := api.Group("/posts")
		{
			posts.GET("", controllers.GetPosts)                                       // 获取文章列表
			posts.GET("/:id", controllers.GetPost)                                    // 获取单个文章
			posts.POST("", middleware.AuthMiddleware(), controllers.CreatePost)       // 创建文章
			posts.PUT("/:id", middleware.AuthMiddleware(), controllers.UpdatePost)    // 更新文章
			posts.DELETE("/:id", middleware.AuthMiddleware(), controllers.DeletePost) // 删除文章
		}

		// 我的文章
		api.GET("/my-posts", middleware.AuthMiddleware(), controllers.GetMyPosts)

		// 评论相关路由
		comments := api.Group("/comments")
		{
			comments.POST("", middleware.AuthMiddleware(), controllers.CreateComment)       // 创建评论
			comments.GET("/post/:post_id", controllers.GetComments)                         // 获取文章评论
			comments.DELETE("/:id", middleware.AuthMiddleware(), controllers.DeleteComment) // 删除评论
		}

		// 我的评论
		api.GET("/my-comments", middleware.AuthMiddleware(), controllers.GetMyComments)
	}

	// 启动服务器
	log.Println("服务器启动在 :8080 端口")
	if err := r.Run(":8080"); err != nil {
		log.Fatal("服务器启动失败:", err)
	}
}
